-----------------------------------------------------------------------------
--
-- Module      :  RecentList
-- Copyright   :  (c) Lakshmi Narasimhan
-- License     :  GNU-GPL
--
-- Maintainer  :  <lakshminaras2002 at gmail dot com>
-- Stability   :  provisional
-- Portability :  portable
--
--
--
---------------------------------------------------------------------------------
module RecentList(
    setupRecentList
	)
where

import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import Graphics.UI.Gtk.ModelView as ModelView
import Graphics.UI.Gtk.ModelView.TreeModel as TreeModel
import GhCalcUtils
import Common

-- Currently we do not need the sophistication of a generic type
-- But when the need arises, we have to change this to be a polymorphic
data Command = Command String


getStringFromCommand :: Command -> String
getStringFromCommand (Command str) = str

strToCommand :: String-> Command
strToCommand str = Command str



setupRecentList :: GladeXML -> IO ()
setupRecentList glade_xml = do
    model <- setupRecentListModel glade_xml
    setupRecentListUpdater glade_xml model
    setupSaveHandler glade_xml model
    setupOpenHandler glade_xml model
    setupClearListHandler glade_xml model
    return ()

setupRecentListModel :: GladeXML -> IO(ListStore Command)
setupRecentListModel glade_xml = do
    let commandList = []::([Command])
    store <- listStoreNew (commandList)
    view <- xmlGetWidget glade_xml castToTreeView "RecentList"
    treeViewSetModel view store
    treeViewSetHeadersVisible view True
    col1 <- ModelView.treeViewColumnNew
    treeViewColumnSetTitle col1 "Recent List"
    renderer1 <- ModelView.cellRendererTextNew
    cellLayoutPackStart col1 renderer1 True
    cellLayoutSetAttributes col1 renderer1 store $ \(Command str)  -> [ ModelView.cellText := str  ]
    treeViewInsertColumn view col1 0
    return store

setupRecentListUpdater :: GladeXML -> ListStore Command -> IO ()
setupRecentListUpdater glade_xml model = do
    -- When = button is pressed we need to add an entry into the recent list --
    formulaEntry <- xmlGetWidget glade_xml castToEntry "tFormula"
    resultEntry <- xmlGetWidget glade_xml castToEntry "tResultEntry"
    view <- xmlGetWidget glade_xml castToTreeView "RecentList"
    eqButton <- xmlGetWidget glade_xml castToButton	"bEnter"
    onClicked eqButton (recentListUpdater formulaEntry model)
    
    errorLabel <- xmlGetWidget glade_xml castToLabel "lErrorStatus"
    -- When an entry in the list is pressed, we need to populate it in the formula entry
    onRowActivated view (\path col -> do
                                      (Just iter) <- ModelView.treeModelGetIter model
                                                                                path
                                      (Command str) <- ModelView.treeModelGetRow
                                                                model iter
                                      entrySetText formulaEntry str
                                      evaluateAndSetResult formulaEntry resultEntry errorLabel
                                      return ()
                        )
    return ()

--recentListUpdater ::
recentListUpdater formulaEntry  model = do
    -- TODO check for duplicates --
    formulaText  <- entryGetText formulaEntry
    listStoreAppend model (Command formulaText)
    return ()

setupClearListHandler :: GladeXML -> ListStore Command -> IO ()
setupClearListHandler glade_xml model = do
  clearListItem <- xmlGetWidget glade_xml castToMenuItem "editClearList"
  onActivateLeaf clearListItem $ do
    listStoreClear model
  return ()

setupSaveHandler :: GladeXML -> ListStore Command -> IO()
setupSaveHandler glade_xml model = do
    saveItem <- xmlGetWidget glade_xml castToMenuItem "fileSaveItem"
    onActivateLeaf saveItem $ do
        maybeIter <- ModelView.treeModelGetIterFirst model
        let checkIter commands Nothing = return commands
            checkIter commands (Just cIter) = do
                command  <- ModelView.treeModelGetRow model cIter
                mIter <- ModelView.treeModelIterNext model cIter
                checkIter (commands ++ (command:[])) mIter
        commandList <- checkIter [] maybeIter
        sessionFileName <- getSessionFileName
        saveContents commandList sessionFileName
    return ()

-- Get the List data from the model --
setupOpenHandler :: GladeXML -> ListStore Command -> IO ()
setupOpenHandler glade_xml  model = do
    openItem <- xmlGetWidget glade_xml castToMenuItem "fileOpenItem"
    onActivateLeaf openItem $ do
	sessionFileName <- getSessionFileName
        commandList <- openContents sessionFileName
        mapM (listStoreAppend model) commandList
        return ()
    return ()

saveContents :: [Command] -> FilePath -> IO ()
saveContents commandList fileName = do
    let strList =   map getStringFromCommand commandList
    let strToWrite = concat (map (\s -> s ++ "\n") strList)
    writeFile fileName strToWrite
    return ()

openContents :: FilePath -> IO [Command]
openContents fileName = do
    contents <- readFile fileName
    let strList = lines contents
    let commandList = map strToCommand strList
    return commandList

